import request from '@/utils/request'

/**
 * 文件上传
 * @param {FormData} data - 文件数据
 * @returns {Promise} 上传结果
 * @example
 * // 使用示例
 * const formData = new FormData()
 * formData.append('file', file)
 * formData.append('type', 'image')
 * uploadFile(formData)
 *
 * // 响应示例
 * {
 *   "code": 200,
 *   "message": "上传成功",
 *   "data": {
 *     "url": "https://example.com/uploads/image.jpg",
 *     "filename": "image.jpg",
 *     "size": 1024
 *   }
 * }
 */
export function uploadFile(data) {
  return request({
    url: '/api/admin/goods/add',
    method: 'post',
    data,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  }).catch((error) => {
    // 如果API不存在，返回模拟数据
    if (error.message && error.message.includes('could not be found')) {
      const file = data.get('file')
      return Promise.resolve({
        code: 200,
        message: '模拟上传成功',
        data: {
          url: URL.createObjectURL(file),
          filename: file.name,
          size: file.size,
          isMock: true,
        },
      })
    }
    throw error
  })
}

/**
 * 图片上传
 * @param {FormData} data - 图片数据
 * @returns {Promise} 上传结果
 */
export function uploadImage(data) {
  return request({
    url: '/api/admin/upload/image',
    method: 'post',
    data,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  }).catch((error) => {
    // 如果API不存在，返回模拟数据
    if (error.message && error.message.includes('could not be found')) {
      const file = data.get('file')
      return Promise.resolve({
        code: 200,
        message: '模拟上传成功',
        data: {
          url: URL.createObjectURL(file),
          filename: file.name,
          size: file.size,
          isMock: true,
        },
      })
    }
    throw error
  })
}
